<template>
	<view class="loginBox">
		<!-- 头像 -->
		<uni-icons class="icon" type="contact-filled" size="100"></uni-icons>

		<!-- 登录按钮 -->
		<button class="btnLogin" type="primary" @click="getuserinfo">一键登录</button>

		<!-- tips提示 -->
		<view class="tips">登录尽享更多权益</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'

	export default {
		name: "my-login",
		data() {
			return {

			};
		},
		computed: {
			...mapState('m_address', ['token', 'redirectInfo'])
		},
		methods: {
			...mapMutations('m_address', ['updateUserInfo', 'updateToken', 'updateRedirectInfo']),
			getuserinfo(e) {
				uni.getUserProfile({
					desc: '登录账户',
					success: (res) => {
						this.updateUserInfo(res.userInfo)
						this.getToken(res)
						this.updateRedirectInfo({
							openType:'switchTab',
							from:'/pages/cart/cart'
						})
					},
					fail(err) {
						uni.$showmsg('您取消了登录授权')
					}
				})
			},
			navigateBack(){
				if(this.redirectInfo && this.redirectInfo.openType === 'switchTab'){
					uni.switchTab({
						url:this.redirectInfo.from,
						complete:()=>{
							this.updateRedirectInfo(null)
						}
					})
				}
			},
			async getToken(info) {
				const [err, res] = await uni.login().catch(err => err)
				if(err || res.errMsg !== 'login:ok') return uni.$showmsg('登录失败')
				
				// 设置参数
				const query = {
					code:res.code,
					rawData:info.rawData,
					signature:info.signature,
					encryptedData:info.encryptedData,
					iv:info.iv
				}
				
				const {data: loginResult} = await uni.$http.post('/api/public/v1/users/wxlogin', query)
				// if(loginResult.meta.status !== 200) return uni.$showmsg('登录失败')
				this.updateToken('123')
				this.navigateBack()
			}
		}
	}
</script>

<style lang="scss">
	.loginBox {
		background-color: #f8f8f8;
		height: 750rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		position: relative;
		overflow: hidden;

		&::after {
			content: '';
			display: block;
			clear: both;
			width: 100%;
			height: 100rpx;
			background-color: white;
			position: absolute;
			bottom: 0;
			border-radius: 100%;
			transform: translateY(50%);
		}

		.btnLogin {
			border-radius: 200rpx;
			width: 80%;
			font-size: 32rpx;
			margin-bottom: 20rpx;
		}

		.tips {
			font-size: 24rpx;
			color: gray;
		}
	}
</style>
